#!/usr/bin/env python
# coding=utf-8

import urllib, json, sys
from optparse import OptionParser

def listcores():
    status_cmd  = baseurl + core_admin_url + urllib.urlencode({'action':'status','wt':'json'})
    cores       = []

    res         = urllib.urlopen(status_cmd)
    data        = json.loads(res.read())

    core_data   = data['status']

    for core_name in core_data:
        cores.append(core_name)

    return cores

def solrping(core):
    ping_cmd = baseurl + core + '/admin/ping?' + urllib.urlencode({'wt':'json'})
    
    res = urllib.urlopen(ping_cmd)
    data = json.loads(res.read())

    status = data.get('status')

    return status

def main():
    global baseurl, core_admin_url, threshold_warn, threshold_crit

    cmd_parser = OptionParser(version="%prog 0.1")
    cmd_parser.add_option("-p", "--port", type="string", action="store", dest="solr_server_port", help="SOLR Server port")
    cmd_parser.add_option("-W", "--webapp", type="string", action="store", dest="solr_server_webapp", help="SOLR Server webapp path")
   
    (cmd_options, cmd_args) = cmd_parser.parse_args()

    if not (cmd_options.solr_server_port and cmd_options.solr_server_webapp):
        cmd_parser.print_help()
        return(3)

    solr_server         = "127.0.0.1"
    solr_server_port    = cmd_options.solr_server_port
    solr_server_webapp  = cmd_options.solr_server_webapp

    #core_admin_url      = 'admin/cores?'
	core_admin_url      = 'core1/admin/'
    baseurl             = 'http://' + solr_server + ':' + solr_server_port + '/' +  solr_server_webapp + '/'

    pingerrors          = []

    try:
        cores = listcores()
    except IOError as (errno, strerror):
        print "mailstatedes=请求遇到IO异常,疑似宕机 statedes=请求遇到IO异常,疑似宕机" 
        return(2)
    except (ValueError, TypeError):
        print "mailstatedes=不能格式化指标信息,疑似宕机 statedes=不能格式化指标信息,疑似宕机" 
        return(3)
    except:
        print "mailstatedes=不能获取指标信息,疑似宕机 statedes=不能获取指标信息,疑似宕机" 
        return(3)

    # XXX: This is ugly...
    try:
        for core in cores:
            if solrping(core) != 'OK':
                pingerrors.append(core)
    except IOError as (errno, strerror):
        print "mailstatedes=不能获取指标信息,疑似宕机 statedes=不能获取指标信息,疑似宕机" 
        return(2)
    except KeyError as strerror:
        if 'slave' in strerror: 
            print "mailstatedes=缺少监控必要参数-r statedes=缺少监控必要参数-r" 
            return(2)
        else:
            print "mailstatedes=不能获取指标信息,疑似宕机 statedes=不能获取指标信息,疑似宕机" 
            return(3)
    
    if pingerrors:
        print "mailstatedes=不能获取指标信息,疑似宕机 statedes=不能获取指标信息,疑似宕机" 
        return(2)
    else:
        print "mailstatedes=状态正常 statedes=状态正常" 
        return(0)

if __name__ == '__main__':
    sys.exit(main())
    
